﻿using Microsoft.Win32;
using Prism.Commands;
using Prism.Events;
using Prism.Regions;
using Prism.Services.Dialogs;
using SmartPlant.Core;
using SmartPlant.Core.Mvvm;
using SmartPlant.Model;
using SmartPlant.Model.Biz;
using SmartPlant.Services.Interfaces;
using SmartPlant.WinCore;
using SmartPlant.WinCore.Helper;
using System.Collections.ObjectModel;
using System.IO;
using System.Windows.Input;
using Unity;
using System.Linq;

namespace SmartPlant.Modules.Base.ViewModels
{
    public class TemplateInputViewModel : ListRegionViewModel<Report>
    {
        private int _templateType = 0;
        private DelegateCommand<string> _downloadFileCommand;
        private DelegateCommand<string> _uploadFileCommand;
        private DelegateCommand<object> _uploadAllFileCommand;
        private DelegateCommand _deleteFileCommand;
        private DelegateCommand _editTemplateCommand;
        private ITemplateSettingService _templateSettingService;
        private IAchievementService _achievementService;
        private IImportUtilityService _importUtilityService;
        private readonly IEventAggregator _eventAggregator;

        public TemplateInputViewModel(
            int templateType,
            IRegionManager regionManager,
            ITemplateSettingService templateSettingService,
            IUnityContainer unityContainer,
            IDialogService dialogService,
            IEventAggregator eventAggregator,
            IAchievementService achievementService,
            IImportUtilityService importUtilityService) :
            base(regionManager, unityContainer, dialogService)
        {
            _templateType = templateType;
            _templateSettingService = templateSettingService;
            _eventAggregator = eventAggregator;
            _achievementService = achievementService;
            _importUtilityService = importUtilityService;
        }

        public ICommand UploadAllFileCommand
        {
            get
            {
                if (_uploadAllFileCommand != null) return _uploadAllFileCommand;
                _uploadAllFileCommand = new DelegateCommand<object>(onUpLoadAllCommandAsync);
                return _uploadAllFileCommand;
            }
        }

        public ICommand UploadFileCommand
        {
            get
            {
                if (_uploadFileCommand != null) return _uploadFileCommand;
                _uploadFileCommand = new DelegateCommand<string>(onUpLoadCommandAsync);
                return _uploadFileCommand;
            }
        }

        public ICommand DownloadFileCommand
        {
            get
            {
                if (_downloadFileCommand != null) return _downloadFileCommand;
                _downloadFileCommand = new DelegateCommand<string>(onDownLoadCommandAsync);
                return _downloadFileCommand;
            }
        }

        public ICommand DeleteFileCommand
        {
            get
            {
                if (_deleteFileCommand != null) return _deleteFileCommand;
                _deleteFileCommand = new DelegateCommand(onDeleteFileCommandAsync);
                return _deleteFileCommand;
            }
        }

        public ICommand EditTemplateCommand
        {
            get
            {
                if (_editTemplateCommand != null) return _editTemplateCommand;
                _editTemplateCommand = new DelegateCommand(onEditTemplateCommandAsync);
                return _editTemplateCommand;
            }
        }
        private async void onEditTemplateCommandAsync()
        {
            if (SelectObj == null)
            {
                Dialog.ShowAltert("请先选择需要编辑的模板对象！！！");
                return;
            }
            var para = new DialogParameters();
            para.Add("ReportID", SelectObj.ReportId.ToString());
            para.Add("Name", SelectObj.Name);
            para.Add("Parameters", SelectObj.Parameters);
            para.Add("InOrOut", SelectObj.InOrOut);
            para.Add("Type", SelectObj.Type);
            para.Add("Description", SelectObj.Description);
            para.Add("Generatefunc", SelectObj.GenerateFunc);
            para.Add("Sql", SelectObj.SQL);
            para.Add("TemplatePath", SelectObj.TemplatePath);
            Dialog.ShowDialog("TemplateSettingEdit", para,
                d =>
                {
                    if (d.Result == ButtonResult.OK)
                    {
                        OnInitPage(null);
                        _eventAggregator.GetEvent<TemplateChangedEvent>()
                        .Publish((TemplateType)_templateType);
                    }
                });
        }

        private async void onDeleteFileCommandAsync()
        {
            if (SelectObj == null)
            {
                Dialog.ShowAltert("请先选择需要删除的模板！！！");
                return;
            }
            string proId = GlobalObject.CurrentProject.ProjId.ToString();
            var result = await _templateSettingService.DeleteTemplateAsync(proId, _templateType, SelectObj);
            if (result)
            {
                OnInitPage(null);//刷新页面内容
                _eventAggregator.GetEvent<TemplateChangedEvent>()
                                        .Publish((TemplateType)_templateType);//发布事件，参数为_templateType,索引导入模块有订阅
            }
        }

        private async void onDownLoadCommandAsync(string fileType)
        {
            if (SelectObj == null)
            {
                Dialog.ShowAltert("请先选择需要编辑的模板！！！");
                return;
            }
            string templatename = ".xlsx";
            string fileFilter = "Excel文件 *.xlsx|*.xlsx";
            if (fileType.ToLower() == "xml")
            {
                templatename = ".xml";
                fileFilter = "XML文件 *.xml|*.xml";
            }

            //templatename = SelectObj.Name + templatename;

            string proId = GlobalObject.CurrentProject.ProjId.ToString();

            try
            {
                var postObj = SelectObj.CloneObject();
                postObj.Name += templatename;
                RESTfulResult<Stream> result = new RESTfulResult<Stream>();
                if (SelectObj.InOrOut == 0)
                {
                    result = await _importUtilityService.DownloadTemplateFileAsync(proId, postObj);
                }
                else
                {
                    result = await _achievementService.DownloadTemplateFileAsync(proId, postObj);
                }
                if (!result.succeeded)
                {
                    LoggerHelper.Current.Error(result.errors.ToString());
                    Dialog.ShowAltert(result.errors.ToString());
                    return;
                }
                var saveFileDialog = new SaveFileDialog
                {
                    Filter = fileFilter,
                    FileName = postObj.Name,
                };
                using var stream = result.data;
                if (saveFileDialog.ShowDialog() == true)
                {
                    var _fielPath = saveFileDialog.FileName;
                    await FileHelper.WriteFileStreamAsync(stream, _fielPath);
                    var rMessage = "下载模板文件到本地成功，请编辑后重新上传！！！";
                    Dialog.ShowAltert(rMessage);
                    return;
                }
            }
            catch (Exception x)
            {
                var xMessage = $"获取远程服务器数据失败：{x.Message}！！！";
                LoggerHelper.Current.Error(xMessage, x);
                Dialog.ShowAltert(xMessage);
            }
        }

        private async void onUpLoadCommandAsync(string fileType)
        {
            if (SelectObj == null)
            {
                Dialog.ShowAltert("请先选择需要上传的模板对象！！！");
                return;
            }

            string proId = GlobalObject.CurrentProject.ProjId.ToString();
            string templatename = ".xlsx";
            string fileFilter = "Excel文件 *.xlsx|*.xlsx";
            if (fileType.ToLower() == "xml")
            {
                templatename = ".xml";
                fileFilter = "XML文件 *.xml|*.xml";
            }
            templatename = SelectObj.Name + templatename;

            var openFileDialog = new OpenFileDialog
            {
                Filter = fileFilter,
            };

            if (openFileDialog.ShowDialog() == true)
            {
                try
                {
                    using Stream stream = openFileDialog.OpenFile();
                    bool r = false;
                    if (SelectObj.InOrOut == 0)
                    {
                        r = await _importUtilityService.UploadTemplateFileAsync(proId, (int)SelectObj.Type, SelectObj.TemplatePath, stream, templatename);
                    }
                    else
                    {
                        r = await _achievementService.UploadTemplateFileAsync(proId, (int)SelectObj.Type, SelectObj.TemplatePath, stream, templatename);
                    }
                    if (r)
                        Dialog.ShowAltert("上传文件至远程服务器成功！！！");
                }
                catch (Exception x)
                {
                    var xMessage = $"上传文件至远程服务器失败：{x.Message}！！！";
                    LoggerHelper.Current.Error(xMessage, x);
                    Dialog.ShowAltert(xMessage);
                }
            }
        }

        private void onUpLoadAllCommandAsync(object obj)
        {
            Dialog.ShowDialog("TemplateSettingNew",
                new DialogParameters($"templateType={_templateType}"),
                d =>
                {
                    if (d.Result == ButtonResult.OK)
                    {
                        OnInitPage(null);
                        _eventAggregator.GetEvent<TemplateChangedEvent>()
                        .Publish((TemplateType)_templateType);
                    }
                });
        }

        protected override async void OnInitPage(object obj)
        {
            try
            {
                string proId = GlobalObject.CurrentProject.ProjId.ToString();
                var list = await _templateSettingService.GetTemplateLisAsync(proId);
                list = list.Where(x => x.Type == (TemplateType)_templateType).ToList();
                DataList.Clear();
                DataList.AddRange(list);
            }
            catch (Exception x)
            {
                var xMessage = $"模板数据加载失败：{x.Message}！！！";
                LoggerHelper.Current.Error(xMessage, x);
                Dialog.ShowAltert(xMessage);
            }
        }
    }
}